from sanic.views import HTTPMethodView
from sanic.response import text,json
import time
from processing.other_func import ProToken,Sercret_all,Serialization,Random_id,date_format
import json as jn
import re
from processing.comm import sqlPaging,sqlOrder,set_status
from processing.Sql_DataFrom import ProJosn

class pluginAdd(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip
        html_data = request.json
        pluginId = Random_id(32,"PLUGIN")
        try:
            sql = """
                insert into plugin(plugin_id,title,image,plugsDescribe,plugsType,paths,status,ctime) VALUES(%s,%s,%s,%s,%s,%s,%s,now())
            """
            db.insert(sql,(pluginId,
                           html_data['title'],
                           html_data['image'],
                           html_data['plugsDescribe'],
                           html_data['plugsType'],
                           html_data['paths'],
                           set_status(html_data['status'])))
            return json({'code': 200, 'message': "添加成功!"})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/plugin/add', error))
            data = {
                'code':500,
                'message':'后端报错!'
            }
            return json(data)
class pluginList(HTTPMethodView):
    async def get(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip
        plugin_id = request.args.get('plugin_id') or ''
        pageNum = int(request.args.get('pageNum', 1))
        pageSize = int(request.args.get('pageSize', 10))
        keyword = request.args.get('keyword', '')
        try:
            sql = """
                select plugin_id,title,image,plugsDescribe,plugsType,paths,status from plugin 
            """

            tol = f""" SELECT COUNT(*) FROM plugin """
            if plugin_id != 'all':
                sql += f" where plugin_id='{plugin_id}' "
                tol = f""" SELECT COUNT(*) FROM plugin where plugin_id='{plugin_id}' """


                if keyword:
                    sql += f" and  title LIKE '%{keyword}%' "
                    tol += f" and  title LIKE '%{keyword}%' "
            else:
                if keyword:
                    sql += f" where title LIKE '%{keyword}%' "
                    tol += f" where title LIKE '%{keyword}%' "

            sql = sqlOrder(sql)
            sql = sqlPaging(pageNum,pageSize,sql)

            find_data = db.find_all(sql)
            tol_data = db.find_one(tol)

            if find_data:
                data = ProJosn(find_data,sql)
            else:
                data = []
            return json({'code': 200,'data':{
                'list':data,
                'total':tol_data[0]
            }, 'message': "请求成功!"})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/plugin/list', error))
            data = {
                'code':500,
                'message':'后端报错!'
            }
            return json(data)
class pluginDelete(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip

        html_data = request.json

        try:

            sql = "delete from plugin where plugin_id=%s"

            db.delete(sql, (html_data['plugin_id']))

            return json({'code': 200, 'message': "删除成功!"})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/plugin/delete', error))
            data = {
                'code':500,
                'message':'后端报错!'
            }
            return json(data)
class pluginUpdate(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip
        html_data = request.json
        try:
            sql = """
                        update plugin set title=%s,image=%s,plugsDescribe=%s,plugsType=%s,paths=%s,status=%s,ctime=now() where plugin_id=%s
                    """
            db.update(sql, (
                html_data['title'],
                html_data['image'],
                html_data['plugsDescribe'],
                html_data['plugsType'],
                html_data['paths'],
                set_status(html_data['status']),
                html_data['plugin_id'],  # 不能为空
            ))

            return json({'code': 200, 'message': "编辑成功!"})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/plugin/update', error))
            data = {
                'code':500,
                'message':'后端报错!'
            }
            return json(data)
class pluginMyPlugin(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip
        html_data = request.json
        pageNum = int(request.args.get('pageNum', 1))
        pageSize = int(request.args.get('pageSize', 100))
        plugin_id = (request.args.get('plugin_id', ''))
        keyword = request.args.get('keyword', '')
        try:
            sql = """
                        select plugin_id from a_users where user_id=%s
                    """

            sql_find_plugin = """
                        select plugin_id,title,image,plugsDescribe,plugsType,paths,status from plugin 
                    """
            data = db.find_all(sql,(user_id))
            sum = 0
            tol_data = 0
            tol = f""" SELECT COUNT(*) FROM plugin """
            if data[0][0]:
                for i in data[0][0].split(','):
                    if i:
                        if sum == 0:
                            sql_find_plugin += f" where plugin_id='{i}' "
                            # tol += f" where plugin_id='{i}' "
                        else:
                            sql_find_plugin += f" or plugin_id='{i}' "
                            # tol += f" or plugin_id='{i}' "
                        sum += 1


                tol_data = db.find_one(tol)
                sql_find_plugin = sqlOrder(sql_find_plugin)
                sql_find_plugin = sqlPaging(pageNum,pageSize,sql_find_plugin)
                data = db.find_all(sql_find_plugin)
                data = ProJosn(data, sql_find_plugin)
            else:
                data = []
                tol_data = [0]



            return json({'code': 200, 'message': "请求成功!",'data':{
                'list':data,
                'total':tol_data[0]
            }})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/plugin/myPlugin', error))
            data = {
                'code':500,
                'message':'后端报错!'
            }
            return json(data)

class pluginUserPlugin(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        # user_id = request.app.ctx.user_id
        client_ip = request.ip
        html_data = request.json

        try:
            sql = """
                update a_users set plugin_id=%s 
            """
            if html_data['plugin_ids'] and html_data['users_ids']:
                for i in range(0,len(html_data['users_ids'])):

                    if i == 0:
                        sql += f' where user_id="{html_data["users_ids"][i]}" '
                    else:
                        sql += f' or user_id="{html_data["users_ids"][i]}" '
                db.update(sql, (
                    html_data['plugin_ids']
                ))
            else:
                for i in range(0, len(html_data['users_ids'])):

                    if i == 0:
                        sql += f' where user_id="{html_data["users_ids"][i]}" '
                    else:
                        sql += f' or user_id="{html_data["users_ids"][i]}" '

                db.update(sql, (
                    '',
                ))
            data = {
                'code':200,
                'message':'请求成功!'
            }
            return json(data)
        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/plugin/myPlugin', error))
            data = {
                'code':500,
                'message':'后端报错!'
            }
            return json(data)

# 查询其它用户插件
class pluginOtherUserPlugin(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip
        html_data = request.json
        pageNum = int(request.args.get('pageNum', 1))
        pageSize = int(request.args.get('pageSize', 200))
        keyword = request.args.get('keyword', '')
        try:
            sql = """
                        select plugin_id from a_users where user_id=%s
                    """

            sql_find_plugin = """
                        select plugin_id,title,image,plugsDescribe,plugsType,paths,status from plugin 
                    """
            data = db.find_all(sql, (html_data['user_id']))
            sum = 0
            tol_data = 0
            tol = f""" SELECT COUNT(*) FROM plugin """

            if data[0][0]:
                for i in data[0][0].split(','):
                    if i:
                        if sum == 0:
                            sql_find_plugin += f" where plugin_id='{i}' "
                            # tol += f" where plugin_id='{i}' "
                        else:
                            sql_find_plugin += f" or plugin_id='{i}' "
                            # tol += f" or plugin_id='{i}' "
                        sum += 1

                tol_data = db.find_one(tol)
                sql_find_plugin = sqlOrder(sql_find_plugin)
                sql_find_plugin = sqlPaging(pageNum, pageSize, sql_find_plugin)
                data = db.find_all(sql_find_plugin)
                data = ProJosn(data, sql_find_plugin)
            else:
                data = []
                tol_data = [0]

            return json({'code': 200, 'message': "请求成功!", 'data': {
                'list': data,
                'total': tol_data[0]
            }})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/plugin/myPlugin', error))
            data = {
                'code': 201,
                'message': '搜索不能为空!'
            }
            return json(data)

# 查询用户插件权限
class checkPlugin(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip
        html_data = request.json
        try:

            sql =  """
                select plugin_id from a_users where user_id=%s
            """

            res = db.find_one(sql,html_data['user_id'])

            if res[0]:
                if html_data['plugin_id'] in res[0].split(','):
                    data = {
                        'code': 200,
                        'data':True,
                        'message': '请求成功!'
                    }
                else:
                    data = {
                        'code': 201,
                        'data': False,
                        'message': '暂无该插件!'
                    }
            else:
                data = {
                    'code': 400,
                    'data': False,
                    'message': '暂无该用户!'
                }
            return json(data)

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/plugin/myPlugin', error))
            data = {
                'code':500,
                'message':'后端报错!'
            }
            return json(data)
